package com.fsd.admin.listener.activiti;

import com.fsd.admin.model.Z_project;
import com.fsd.admin.service.Z_projectService;
import com.fsd.admin.service.Z_projectscoreService;
import com.fsd.core.util.SpringContextHolder;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.history.HistoricProcessInstance;
import org.springframework.stereotype.Component;

/**
 * ================================
 * 流程正常结束监听，用于修改项目状态
 * @Description:
 * @Author: lumingbao
 * ================================
 */
@Component
public class StopListener implements ExecutionListener {

    private ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

    @Override
    public void notify(DelegateExecution execution) throws Exception{
        Z_projectService projectService = (Z_projectService) SpringContextHolder.getBean("z_projectServiceImpl");
        Z_projectscoreService projectscoreService = (Z_projectscoreService) SpringContextHolder.getBean("z_projectscoreServiceImpl");
        String processInstanceId = execution.getProcessInstanceId();
        HistoricProcessInstance historicProcessInstance = processEngine.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if(historicProcessInstance != null){
            String[] dir = historicProcessInstance.getBusinessKey().split("\\.");
            String projectId = dir[1];
            projectService.updateProjectStatus(projectId, "shtg");

            double score = projectscoreService.getProjectScoreByProjectId(projectId);
            Z_project project = projectService.get(projectId);
            project.setF_netscore(String.valueOf(score));
            projectService.update(project);
        }
    }
}
